<template>
  <div class="home-page">
    <upload 
      action="/api/upload"
      :beforeUpload="beforeUpload"
      @file-uploaded="onFileUploaded">
      <template #uploaded="dataProps">
        <div v-if="dataProps && dataProps.uploadedData">
          <img :src="dataProps.uploadedData.data.url" width="500"/>
        </div>
      </template>
    </upload>
    <column-list :list="list" />
    <button
      class="btn btn-outline-primary mt-2 mb-5 mx-auto btn-block w-25"
       @click="loadMorePage" v-if="!isLastPage"
    >
      加载更多
    </button>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted } from 'vue';
import ColumnList from '@/components/ColumnList.vue';
import Upload from '@/components/Upload.vue'
import { useStore } from 'vuex';
import { GlobalDataProps, ImageProps, ResponseType } from '@/types';
import createMessage from '@/components/createMessage';
import useLoadMore from '@/hooks/useLoadMore';

const store = useStore<GlobalDataProps>();
const total = computed(() => store.state.columns.total);
const currentPage = computed(() => store.state.columns.currentPage);
onMounted(() => {
  store.dispatch('fetchColumns', { pageSize: 3 })
});
const list = computed(() => store.getters.getColumns)
const { loadMorePage, isLastPage } = useLoadMore('fetchColumns', total, { pageSize: 3, currentPage: (currentPage.value ? currentPage.value + 1 : 2) })
const beforeUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg';
  if (!isJPG) {
    createMessage("图片格式非法！！！图片只能是 JPG 格式", 'error');
  }
  return isJPG;
}

const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
  createMessage(`上传图片 ID ${rawData.data._id}`, 'success');
}

</script>